package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.common.PageInfo;
import com.itheima.common.ThreadLocalIUtil;
import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public PageInfo<Category> page( Integer page, Integer pageSize) {
        PageInfo<Category> pageInfo=new PageInfo<>();
        Integer start =(page-1) * pageSize;
        List<Category> categorys = categoryMapper.page( start, pageSize);
        pageInfo.setRecords(categorys);
        pageInfo.setSize(pageSize);
        pageInfo.setCurrent(page);
        long count = categoryMapper.count();
        pageInfo.setTotal(count);
        return pageInfo;
    }
    @Override
    public boolean save(Category category) {
        String id = IdUtil.getSnowflakeNextIdStr();
        if (!(category.getId()==null)){
            return false;
        }
        category.setId(id);
        int addcategory = categoryMapper.save(category);
        return addcategory>0;
    }

    @Override
    public boolean update(Category category) {
        if (category.getId()==null){
            return false;
        }
        LocalDateTime ldt = LocalDateTime.now();
        category.setUpdateTime(ldt);
        //设置修改者 使用当前线程的使用者的id
        long id=Thread.currentThread().getId();
        log.info("线程id:{}", id);
        category.setUpdateUser(ThreadLocalIUtil.getId());

        Integer update = categoryMapper.update(category);
        return update>0;
    }



    @Override
    public  List<Category>  getList(Integer type){
        List<Category> list = categoryMapper.getList(type);
        return list;
    }
    @Override
    public boolean delete(String id){
        Integer delete = categoryMapper.delete(id);
        return delete>0;
    }
    @Override
    public Category getById(String id){
        LambdaQueryWrapper<Category> wrapper=new LambdaQueryWrapper<>();
        wrapper.eq(Category::getId,id);
        return categoryMapper.getById(id);
    }

    @Override
    public List<Category> clientGetList() {
        List<Category> list = categoryMapper.clientGetList();
        return list;

    }
}
